/*
 * User: rant
 * Date: Jul 30, 2007
 *
 *
 */
package laMalinche;

import laMalinche.constraint.ConstraintManager;
import laMalinche.constraint.ConstraintRuleListener;
import laMalinche.editableContext.AboutToChangeManager;
import laMalinche.rete.nodes.editing.EditableContextReteRoot;
import laMalinche.rete.rule.ProductionRule;
import laMalinche.ruleTailing.BusinessRelevantPropertyListener;

import java.util.*;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Guice;

/**
 *
 */
public class BasicLaMa implements LaMalinche {
    public static final String DEFAULT_TRIGER = "default";
    private AboutToChangeManager aboutToChangeManager;
    //public for testing
    @Inject
    public EditableContextReteRoot reteRoot;

    private ConstraintManager constraintManager;

    @Inject
    public void setConstraintManager(final ConstraintManager constraintManager) {
        this.constraintManager = constraintManager;
    }

    public void addRelevantPropertyListener(BusinessRelevantPropertyListener listener) {
        final EditableContextReteRoot rete = getRete();
        rete.addRelevantPropertyListener(listener);
    }

    public BasicLaMa() {
        DevMode.clean();
        Injector injector = Guice.createInjector(new LaMaModule());
        DevMode.getInstance().setInjector(injector);
        DevMode.getInstance().getInjector().injectMembers(this);
    }


    public AboutToChangeManager getAboutToChangeManager() {
        return aboutToChangeManager;
    }

    public void setAboutToChangeManager(final AboutToChangeManager aboutToChangeManager) {
        this.aboutToChangeManager = aboutToChangeManager;
        reteRoot.setAboutToChangeManager(aboutToChangeManager);
    }


    public void setConstraintRuleListener(final ConstraintRuleListener constraintRuleListener) {
        constraintManager.setConstraintRuleListener(constraintRuleListener);
    }


    public void add(Set<ProductionRule> rules) {
        for (ProductionRule rule : rules) {
            reteRoot.add(rule);
        }
    }


    public void updateConstraintStatus() {
        constraintManager.updateConstraintStatus();
    }

    public void updateTrigered() {
        LaMaContext.getInstance().getTrigerCondition(DEFAULT_TRIGER).update();
    }

    public void updateTrigered(String s) {
        LaMaContext.getInstance().getTrigerCondition(s).update();
    }


    public void start() {
        reteRoot.updateConditions();
    }

    public void detach() {
        reteRoot.detach();
        LaMaContext.getInstance().detach();
    }

    private EditableContextReteRoot getRete() {
        return reteRoot;
    }

}